package sw6.digipecs.model;

import java.util.ArrayList;
import java.util.List;

import sw6.digipecs.database.DBAdapter;
import sw6.digipecs.database.SituationCursor;
import sw6.digipecs.exceptions.DatabaseException;
import sw6.digipecs.exceptions.IDNotFoundException;
import android.content.Context;

public class Situation {
	
	private DBAdapter mDB;
	private String mName;
	private int mId;

	public Situation(Context context, int id) throws IDNotFoundException {
		SituationCursor cursor;
		
		mDB = new DBAdapter(context);
		mDB.open();
		cursor = mDB.fetchSituation(id);
		
		if (cursor.moveToFirst()) {
			mName = cursor.getName();
			mId = id;
		} else {
			cursor.close();
			mDB.close();
			throw new IDNotFoundException();
		}
		
		cursor.close();
		mDB.close();
	}
	
	public static Situation CreateNew(Context context, String name) throws DatabaseException {
		long id;
		Situation situation;
		
		DBAdapter db = new DBAdapter(context);
		db.open();
		id = db.addSituation(name);
		db.close();
		
		try {
			situation = new Situation(context, (int)id);
		} catch (IDNotFoundException e) {
			throw new DatabaseException();
		}
		
		return situation;
	}
	
	public static List<Situation> getAll(Context context) {
		List<Situation> situations = new ArrayList<Situation>();
		SituationCursor cursor;
		
		DBAdapter db = new DBAdapter(context);
		db.open();
		cursor = db.fetchSituations();
		if (cursor.moveToFirst()) {
			do {
				try {
					situations.add(new Situation(context, cursor.getId()));
				} catch (IDNotFoundException e) { }
			} while (cursor.moveToNext());
		}
		db.close();
		
		return situations;
	}
	
	public String getName() {
		return mName;
	}
	
	public int getId() {
		return mId;
	}

}
